<template>
	<div>
		<u-navbar placeholder title="添加好友" autoBack></u-navbar>
		<div class="search-box">
      <u-search placeholder="请输入完整账号搜索用户" v-model="keyword" :showAction="true" actionText="搜索" @search="searchChange" @custom="searchChange"></u-search>

      <!--			<u-search placeholder="请输入完整账号搜索用户" v-model="keyword" @focus="showAction=true" @blur="showAction=false" @search="searchChange" actionText="搜索" @custom="searchChange" :showAction="showAction"></u-search>-->
<!--			<u-search placeholder="请输入完整账号搜索用户" v-model="keyword" @change="searchChange" :showAction="false"></u-search>-->
		</div>
		<!-- 搜索列表 -->
		<div class="list" v-for="(item,index) in searchUserList" :key="index">
			<Avatar useSkeletonAnimation :url="item.avatar" size="50px" />
			<div class="content ">
				<div class="left">
					<div class="name">{{ item.nick||item.userID }}</div>
					<div class="id">账号:{{item.userID}}</div>
				</div>
				<div class="btn" v-if="item.isFriend===0" @click="addFriend(item.userID)">加为好友</div>
				<div class="gray" v-else-if="item.isFriend===3">等待验证</div>
				<div class="gray" v-else-if="item.isFriend===2">已添加</div>
				<div class="gray" v-else-if="item.isFriend===1">已是好友</div>
			</div>

		</div>
		<div class="empty" v-if="!searchUserList.length">
			<u-empty :icon="empty" :text="keyword?'未搜索到用户':'输入完整账号即可添加好友哦~'"></u-empty>
		</div>
	</div>

</template>

<script lang="ts" setup>
	import { ref, defineProps, reactive, defineEmits, nextTick, watchEffect } from "../../../adapter-vue";
	import {checkUserInfo } from "../../../utils/checkLogin";
	import {
		TUIStore,
		StoreName,
		TUIFriendService,
		TUIUserService,
	} from "@tencentcloud/chat-uikit-engine";
	import { Toast, TOAST_TYPE } from "../../common/Toast/index";
	import empty from "../../../assets/icon/empty.png";
	import Avatar from "../../common/Avatar/index.vue";
	import { onHide, onShow } from "@dcloudio/uni-app"; // 该方法只能用在父组件内，子组件内不生效
	let myUserInfo = ref({})
	let source=ref('')
	//搜索字段
	let keyword = ref('')
	let showAction = ref(false)
	const searchUserList = ref<any>([]);
	const friendList = ref([]);
	// friendList 数据结构中有 profile
	const filterListItem = (list : any) => {
		return list.map((item : { profile : any; }) => { return item.profile });
	};
	const getFriendList = async () => {
		TUIFriendService.getFriendList()
			.then((res : any) => {
				friendList.value = filterListItem(res.data);
			})
			.catch((err : any) => {
				console.warn("getFriendList error:", err);
			});
		// 查询自己的资料
		TUIUserService.getUserProfile().then((res : any) => {
			myUserInfo.value = res.data;
		}).catch((error) => {
		if (error.code === 3003) {
			uni.showToast({
				title: "聊天账号已在其他设备登录",
				icon: "none",
			})
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/tabbar/index'
				})
			}, 1000)
			return null
		}

		uni.showToast({
			title: "查找失败：" + error?.message,
			icon: "none",
			duration: 1000,
		});
	});
	};
	const addFriend = (userId : string) => {
		TUIFriendService.addFriend({
			to: userId,//用户id
			source: 'AddSource_Type_yc',//来源
		}).then((res) => {
			console.log(res,"加好友结果")
			if(res.data.code===0){
				uni.showToast({
					title: "已添加",
					icon: "success"
				})
				searchUserList.value[0].isFriend = 2
			}else{
				uni.showToast({
					title: res.data.message,
					icon: "none"
				})
				searchUserList.value[0].isFriend = 3
			}
			
			
			console.log(searchUserList.value[0].isFriend, "searchUserList.value[0].isFriend=2")
		}).catch((error) => {
			if (error.code == 30525) {
				uni.showToast({
					title: "等待验证",
					icon: "success"
				})
				searchUserList.value[0].isFriend =3
			} else {
				uni.showToast({
					title: error.message,
					icon: "none"
				})
			}
		});
	}
	const searchChange = async () => {+
      -6
		if (keyword.value === '') {
			searchUserList.value = [];
			return
		}
		try {
			console.log(keyword.value+'_'+source.value,"搜索字段")
			// 用户列表里面搜索
			const res : any = await TUIUserService.getUserProfile({
				userIDList: [keyword.value+'_'+source.value],
			});

			let imResponse = JSON.parse(JSON.stringify(res.data))
			console.log(imResponse, "imResponse")
			//搜索出来自己
			if (myUserInfo.value?.userID === imResponse[0].userID) {
				searchUserList.value = [];
				return
			}
			imResponse[0].isFriend = 0
			friendList.value.forEach((item : any) => {
				if (item.userID === imResponse[0].userID) {
					//搜索用户已在好友列表
					imResponse[0].isFriend = 1
				}
			});
			searchUserList.value = imResponse


			console.log(imResponse, searchUserList.value, "imResponse111")
		} catch (error) {
			searchUserList.value = [];
			return;
		}
	};

	onShow(() => {
		TUIStore.watch(StoreName.CUSTOM, {
			IMuserInfo: (data : any) => {
				if (data) {
					source.value=data.source
					getFriendList()
				    checkUserInfo()
				}

			}
		})

	})
</script>

<style lang="scss" setup>
	.search-box {
		padding: 20rpx 30rpx;
		box-sizing: border-box;
		background: #FFF;
	}

	.empty {
		margin-top: 60rpx;
	}

	.list {
		padding: 0 30rpx;
		display: flex;
		align-items: center;

		.content {
			padding: 24rpx 0;
			margin-left: 26rpx;
			border-bottom: 1px solid #ececee;
			width: 80%;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.left {
				width: 70%;

				.name {
					width: 100%;
					font-size: 32rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.id {
					color: #999;
					font-size: 24rpx;
					margin-top: 8rpx;
				}
			}

			.btn {
				color: #ff0012;
				border: 1px solid #ff0012;
				padding: 4rpx 12rpx;
				border-radius: 30rpx;
			}

			.gray {
				color: #ff0012;
			}


		}
	}

	page {
		background: #fff;
	}
</style>